//
//  LogisticsMapViewController.m
//  Logistics
//
//  Created by 锋 on 2018/1/13.
//  Copyright © 2018年 HUYU. All rights reserved.
//

#import "LogisticsMapViewController.h"
#import <QMapKit/QMapKit.h>
#import "NearLogisModel.h"
#import "CompanyHomeViewController.h"

@interface LogisticsMapViewController ()<QMapViewDelegate>
@property (nonatomic, strong) QMapView *mapView;
@property (nonatomic, strong) NSMutableArray<id <QAnnotation> > *annotations;
@property (nonatomic, strong) NSMutableArray *mapAddressArr;
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@end

@implementation LogisticsMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _mapAddressArr = @[].mutableCopy;
    [self setupUI];
    [self requestNearLogistics];
    // Do any additional setup after loading the view.
}

- (void)setupUI {
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"附近物流";
    self.view.backgroundColor = ThemeColor;
    //地图
    self.mapView = [[QMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.mapView.delegate = self;
    //开启定位
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = QUserTrackingModeFollow;
    [self.view addSubview:self.mapView];
}

-(void)mapView:(QMapView *)mapView didSelectAnnotationView:(QAnnotationView *)view {
    if ([view isKindOfClass:[QPinAnnotationView class]]) {
        NSInteger index = view.tag;
        NearLogisModel *model = _mapAddressArr[index];
        CompanyHomeViewController *vc = [[CompanyHomeViewController alloc] init];
        vc.comPanyId = s_str(model.company.ID);
        [self.navigationController pushViewController:vc animated:YES];
//        if (self.mapBlock != nil)
//        {
//            self.mapBlock(model.company.ID);
//        }
//        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (QAnnotationView *)mapView:(QMapView *)mapView viewForAnnotation:(id<QAnnotation>)annotation
{
    if ([annotation isKindOfClass:[QPointAnnotation class]])
    {
        static NSString *pointReuseIndetifier = @"pointReuseIndetifier";
        QPinAnnotationView *annotationView = (QPinAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        
        if (annotationView == nil)
        {
            annotationView = [[QPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndetifier];
        }
        annotationView.canShowCallout = YES;
        UIImage *img = [UIImage imageNamed:@"tubiao"];
        
        annotationView.image = img;
        annotationView.centerOffset = CGPointMake(0, -img.size.height / 2.0);
        annotationView.tag = [annotation.title integerValue];
        
        return annotationView;
    }
    
    return nil;
}

- (UIView *)mapView:(QMapView *)mapView customCalloutForAnnotationView:(QAnnotationView *)annotationView
{
    NSInteger index = annotationView.tag;
    NearLogisModel *model = _mapAddressArr[index];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 40)];
    UILabel *nameLabel = [ZCControl createLabelWithFrame:CGRectMake(0, 0, 60, 40) Font:12 Text:model.company.companyName Color:[UIColor blackColor]];
    [view addSubview:nameLabel];
    
    return view;
}

- (void)setupAnnotations
{
    self.annotations = [NSMutableArray array];
    if (_mapAddressArr.count > 0) {
        NearLogisModel *model = _mapAddressArr[0];
        QPointAnnotation *annotation = [[QPointAnnotation alloc] init];
        annotation.coordinate = CLLocationCoordinate2DMake([model.lat doubleValue],[model.lng doubleValue]);
        annotation.title = [NSString stringWithFormat:@"%d",0];
        [self.annotations addObject:annotation];
        
        for (int i = 0; i < _mapAddressArr.count; i++) {
            if (i != 0) {
                NearLogisModel *model = _mapAddressArr[i];
                annotation = [[QPointAnnotation alloc] init];
                annotation.coordinate = CLLocationCoordinate2DMake([model.lat doubleValue],[model.lng doubleValue]);
                annotation.title = [NSString stringWithFormat:@"%d",i];
                [self.annotations addObject:annotation];
            }
        }
    }
}

- (void)requestNearLogistics
{
    WEAKSELF;
    NSDictionary *dic = @{@"scope":@"30", @"maxSize":@"20", @"lat":[NSString stringWithFormat:@"%lf", _mapView.centerCoordinate.latitude], @"lng":[NSString stringWithFormat:@"%lf", _mapView.centerCoordinate.longitude]};
    [HYBaseHandler requestWithTheFormUrl:SERVER_NearLogisMap Parmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            _mapAddressArr = [NearLogisModel mj_objectArrayWithKeyValuesArray:obj[@"data"]];
            [_mapView removeAnnotations:_annotations];
            [_annotations removeAllObjects];
            [self setupAnnotations];
            [self.mapView addAnnotations:_annotations];
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
    }];
}

/**
 * @brief 用户位置更新后，会调用此函数
 * @param mapView 地图View
 * @param userLocation 新的用户位置
 * @param fromHeading 是否为heading 变化触发，如果为location变化触发,则为NO
 */
- (void)mapView:(QMapView *)mapView didUpdateUserLocation:(QUserLocation *)userLocation fromHeading:(BOOL)fromHeading
{
    NSLog(@"%s fromHeading = %d, location = %@, heading = %@", __FUNCTION__, fromHeading, userLocation.location, userLocation.heading);
    if (_mapView.centerCoordinate.latitude != _coordinate.latitude || _mapView.centerCoordinate.longitude != _coordinate.longitude) {
        [self requestNearLogistics];
    }
    _coordinate = _mapView.centerCoordinate;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
